package top.jacktgq.sxt.bio.ChatRoom.version5.client;

import top.jacktgq.sxt.bio.ChatRoom.version5.utils.ResourceUtils;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * @Author CandyWall
 * @Date 2019/10/22--20:45
 * @Description 客户端接收消息线程
 *                  封装功能：
 *                      1、接收消息
 *                      2、释放资源
 *                      3、重写了run方法
 */
public class Receive implements Runnable {
    private Socket client;
    private DataInputStream dis;
    private Boolean isRunning;

    public Receive(Socket client) {
        this.client = client;
        try {
            dis = new DataInputStream(client.getInputStream());
            isRunning = true;
        } catch (IOException e) {
            e.printStackTrace();
            release();
        }
    }

    private String receive() {
        String content = null;
        try {
            content = dis.readUTF();
        } catch (IOException e) {
            e.printStackTrace();
            release();
        }
        return content;
    }

    //释放资源
    private void release() {
        //停止本次与客户端的通信（接收消息和发送消息）
        this.isRunning = false;
        ResourceUtils.close(dis, client);
    }

    @Override
    public void run() {
        while (isRunning) {
            String content = receive();
            System.out.println("服务器端发来：" +content);
        }
    }
}
